package org.jfk.sys.role;

import org.apache.log4j.Logger;
import org.jfk.core.model.BaseModel;
import org.jfk.core.model.SqlFilter;
import org.jfk.sys.user.User;

import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Table;
import com.jfinal.plugin.activerecord.TableMapping;

/**
 * 
 * @author jxf
 * 2015年8月21日
 */

@SuppressWarnings("serial")
public class Role extends  BaseModel<Role> {
	private static Logger logger = Logger.getLogger(Role.class);	
	public static final Role dao;
	public static final Table table;
	public static final String tableName;
	static {
		dao = new Role();
		table = TableMapping.me().getTable(Role.class);
		tableName = table.getName();
	}
	
	public Page<Role> paginate(RoleController controller){
		String select = " select t1.*,ot1.loginName creator_loginName";
		String from =" from "+tableName +" t1 ";
		String join = " left outer join "+User.tableName+" ot1 on ot1.id=t1.creator";
		String where = " where 1=1 ";
		SqlFilter filter = controller.genJsonFilter();
		
		//处理列表查询的智能搜索
		String search = controller.getPara("search");	

		if (search != null && !"".equals(search.trim())) {
			SqlFilter searchFilter = new SqlFilter();
			searchFilter.add("and", tableName+".id", "eq", search);
			searchFilter.end();
			filter.add(searchFilter);
			controller.setAttr("search", search);
		}
		
		//加工request参数
		controller.addPageAttr();
		
		String sqlExceptSelect = from+join+where+filter.sqlText;
		sqlExceptSelect = sqlExceptSelect + controller.sqlSort;
		logger.debug(filter);
		Page<Role> page = dao.paginate(controller.currentPage, controller.limit, select, sqlExceptSelect, filter.params.toArray());
		return page;
	}
	
	public Role findById(Object id){
		return dao.findFirst("select t1.*,ot1.loginName creator_loginName"
				+ " from "+tableName+" t1 "
				+ " left outer join "+User.tableName+" ot1 on t1.creator=ot1.id"
				+ " where t1.id=?",id);
	}
	
	/**
	 * 根据用户名判断是否管理员角色
	 * @param userName
	 * @return
	 */
	public boolean isAdmin(String userName){
		Role role = Role.dao.findFirst("select * from jfk_role a left join jfk_user_role b on a.id=b.roleId left join jfk_user c on b.userId=c.id where a.id = 1 and c.loginName = ?",userName);
		if (role == null){
			return false;
		}else{
			return true;
		}
	}

	/**
	 * 根据用户ID判断是否管理员角色
	 * @param userId
	 * @return
	 */
	public boolean isAdmin(int userId){
		Role role = Role.dao.findFirst("select * from jfk_role a left join jfk_user_role b on a.id=b.roleId left join jfk_user c on b.userId=c.id where a.id = 1 and c.id = ?",userId);
		if (role == null){
			return false;
		}else{
			return true;
		}
	}
}
